<!--
  智慧社区管理系统 - 安保路线新增页面
  按照报修服务页面风格实现
  
  @author Wu.Liang
  @date 2025-01-30
  @description 安保路线新增功能，支持基于数据权限的社区选择
-->
<template>
  <view class="route-container">
    <!-- 服务说明区域 -->
    <view class="intro-section">
      <view class="intro-content">
        <u-icon name="shield" color="#409eff" size="24"></u-icon>
        <text class="intro-text">请详细填写安保路线信息，我们会尽快为您配置</text>
      </view>
    </view>

    <!-- 路线表单 -->
    <view class="form-container">
      <u-form :model="formData" ref="formRef" :rules="rules">
        <!-- 路线类型 -->
        <view class="form-section">
          <view class="section-title">
            <u-icon name="list" color="#409eff" size="16"></u-icon>
            <text>路线类型</text>
            <text class="required">*</text>
          </view>
          <view class="type-grid">
            <view 
              v-for="type in routeTypes" 
              :key="type.value"
              class="type-item"
              :class="{ active: formData.routeType === type.value }"
              @click="selectRouteType(type.value)"
            >
              <u-icon :name="getTypeIcon(type.value)" color="currentColor" size="20"></u-icon>
              <text>{{ type.label }}</text>
            </view>
          </view>
        </view>
        
        <!-- 路线名称 -->
        <view class="form-section">
          <view class="section-title">
            <u-icon name="edit-pen" color="#409eff" size="16"></u-icon>
            <text>路线名称</text>
            <text class="required">*</text>
          </view>
          <u-input 
            v-model="formData.routeName"
            placeholder="请输入路线名称"
            maxlength="200"
            class="form-input"
          ></u-input>
        </view>
        
        <!-- 所属社区 -->
        <view class="form-section">
          <view class="section-title">
            <u-icon name="map" color="#409eff" size="16"></u-icon>
            <text>所属社区</text>
            <text class="required">*</text>
          </view>
          <view class="address-selector" @click="openCommunityPicker">
            <view class="address-display">
              <text v-if="formData.communityId" class="selected-address">
                {{ formData.communityName }}
              </text>
              <text v-else class="placeholder">请选择所属社区</text>
            </view>
            <u-icon name="arrow-down" color="#999" size="16"></u-icon>
          </view>
        </view>
        
        <!-- 巡逻频次 -->
        <view class="form-section">
          <view class="section-title">
            <u-icon name="clock" color="#409eff" size="16"></u-icon>
            <text>巡逻频次</text>
            <text class="required">*</text>
          </view>
          <view class="frequency-grid">
            <view 
              v-for="frequency in frequencyTypes" 
              :key="frequency.value"
              class="frequency-item"
              :class="{ active: formData.frequency === frequency.value }"
              @click="selectFrequency(frequency.value)"
            >
              <u-icon :name="frequency.icon" color="currentColor" size="16"></u-icon>
              <text>{{ frequency.label }}</text>
            </view>
          </view>
        </view>
        
        <!-- 预计时长 -->
        <view class="form-section">
          <view class="section-title">
            <u-icon name="timer" color="#409eff" size="16"></u-icon>
            <text>预计时长（分钟）</text>
            <text class="required">*</text>
          </view>
          <u-input 
            v-model="formData.durationMinutes"
            placeholder="请输入预计时长"
            type="number"
            maxlength="10"
            class="form-input"
          ></u-input>
        </view>
        
        <!-- 路线描述 -->
        <view class="form-section">
          <view class="section-title">
            <u-icon name="file-text" color="#409eff" size="16"></u-icon>
            <text>路线描述</text>
          </view>
          <u-textarea 
            v-model="formData.description"
            placeholder="请详细描述路线信息，包括巡逻重点、注意事项等"
            maxlength="500"
            :auto-height="true"
            class="form-textarea"
          ></u-textarea>
        </view>
        
        <!-- 检查点配置 -->
        <view class="form-section">
          <view class="section-title">
            <u-icon name="location" color="#409eff" size="16"></u-icon>
            <text>检查点配置</text>
            <text class="optional">（可选）</text>
          </view>
          
          <!-- 检查点列表 -->
          <view class="checkpoint-list">
            <view 
              v-for="(checkpoint, index) in checkpoints" 
              :key="index"
              class="checkpoint-item"
            >
              <view class="checkpoint-header">
                <text class="checkpoint-title">检查点 {{ index + 1 }}</text>
                <u-icon 
                  name="close" 
                  size="16" 
                  color="#f56c6c" 
                  @click="removeCheckpoint(index)"
                  class="remove-btn"
                ></u-icon>
              </view>
              
              <view class="checkpoint-form">
                <view class="form-row">
                  <view class="form-field">
                    <text class="field-label">检查点名称</text>
                    <u-input 
                      v-model="checkpoint.name"
                      placeholder="请输入检查点名称"
                      class="field-input"
                    ></u-input>
                  </view>
                </view>
                
                <view class="form-row">
                  <view class="form-field">
                    <text class="field-label">检查内容</text>
                    <u-textarea 
                      v-model="checkpoint.description"
                      placeholder="请输入需要检查的内容"
                      :auto-height="true"
                      class="field-textarea"
                    ></u-textarea>
                  </view>
                </view>
              </view>
            </view>
          </view>
          
          <!-- 添加检查点按钮 -->
          <view class="add-checkpoint-btn" @click="addCheckpoint">
            <u-icon name="plus" size="16" color="#409eff"></u-icon>
            <text>添加检查点</text>
          </view>
        </view>
      </u-form>
    </view>

    <!-- 提交按钮 -->
    <view class="submit-section">
      <u-button 
        type="primary" 
        @click="handleSubmit"
        :loading="submitting"
        class="submit-btn"
      >
        {{ submitting ? '创建中...' : '创建路线' }}
      </u-button>
    </view>

  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { createSecurityRoute } from '@/api/security'
import { regionApi } from '@/api/region'

// 响应式数据
const submitting = ref(false)

// 表单引用
const formRef = ref(null)

// 表单数据
const formData = reactive({
  routeName: '',
  routeType: '',
  communityId: '',
  communityName: '',
  frequency: '',
  durationMinutes: '',
  description: ''
})

// 检查点数据
const checkpoints = ref([])


// 路线类型选项
const routeTypes = [
  { label: '日常巡逻', value: 'DAILY' },
  { label: '夜间巡逻', value: 'NIGHT' },
  { label: '特殊巡逻', value: 'SPECIAL' },
  { label: '应急巡逻', value: 'EMERGENCY' }
]

// 巡逻频次选项
const frequencyTypes = [
  { label: '每小时', value: 'HOURLY', icon: 'clock' },
  { label: '每2小时', value: 'EVERY_2_HOURS', icon: 'clock' },
  { label: '每4小时', value: 'EVERY_4_HOURS', icon: 'clock' },
  { label: '每6小时', value: 'EVERY_6_HOURS', icon: 'clock' },
  { label: '每8小时', value: 'EVERY_8_HOURS', icon: 'clock' },
  { label: '每12小时', value: 'EVERY_12_HOURS', icon: 'clock' },
  { label: '每天', value: 'DAILY', icon: 'calendar' }
]

// 社区选择器数据
const communityColumns = ref([[]])

// 表单验证规则
const rules = reactive({
  routeName: [
    { required: true, message: '请输入路线名称', trigger: 'blur' }
  ],
  routeType: [
    { required: true, message: '请选择路线类型', trigger: 'change' }
  ],
  communityId: [
    { required: true, message: '请选择所属社区', trigger: 'change' }
  ],
  frequency: [
    { required: true, message: '请选择巡逻频次', trigger: 'change' }
  ],
  durationMinutes: [
    { required: true, message: '请输入预计时长', trigger: 'blur' },
    { pattern: /^\d+$/, message: '请输入有效的数字', trigger: 'blur' }
  ]
})

// 网格选择器方法
const selectRouteType = (value) => {
  formData.routeType = value
}

const selectFrequency = (value) => {
  formData.frequency = value
}

// 获取类型图标
const getTypeIcon = (type) => {
  const iconMap = {
    'DAILY': 'sun',
    'NIGHT': 'moon',
    'SPECIAL': 'star',
    'EMERGENCY': 'warning'
  }
  return iconMap[type] || 'shield'
}

// 社区选择器方法
const openCommunityPicker = async () => {
  try {
    // 如果数据为空，先尝试重新加载
    if (!communityColumns.value || communityColumns.value.length === 0 || communityColumns.value[0].length === 0) {
      await loadCommunityList()
    }
    
    // 检查数据是否加载成功
    if (communityColumns.value && communityColumns.value.length > 0 && communityColumns.value[0].length > 0) {
      // 使用原生选择器
      const communityNames = communityColumns.value[0].map(item => item.label)
      
      uni.showActionSheet({
        itemList: communityNames,
        success: (res) => {
          const selectedCommunity = communityColumns.value[0][res.tapIndex]
          formData.communityId = selectedCommunity.value
          formData.communityName = selectedCommunity.label
        },
        fail: (err) => {
          console.log('取消选择社区')
        }
      })
    } else {
      uni.showToast({
        title: '暂无社区数据',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('打开社区选择器失败:', error)
    uni.showToast({
      title: '加载社区数据失败',
      icon: 'none'
    })
  }
}



// 检查点相关方法
const addCheckpoint = () => {
  checkpoints.value.push({
    name: '',
    description: ''
  })
}

const removeCheckpoint = (index) => {
  checkpoints.value.splice(index, 1)
}


// 加载社区列表
const loadCommunityList = async () => {
  try {
    // 调用后端CommunityController.getCommunityList(CommunityQueryDTO)
    const queryDTO = {
      // 可以根据需要添加查询参数
      // pageNum: 1,
      // pageSize: 1000,
      // name: '',
      // status: 1
    }
    const response = await regionApi.getCommunityList(queryDTO)
    
    // 处理不同的响应格式
    let communityList = []
    
    if (response) {
      // 情况1: 标准响应格式 {success: true, data: [...]}
      if (response.success && response.data) {
        if (Array.isArray(response.data)) {
          communityList = response.data
        } else if (response.data.list && Array.isArray(response.data.list)) {
          // 情况2: 分页响应格式 {success: true, data: {list: [...]}}
          communityList = response.data.list
        } else if (response.data.records && Array.isArray(response.data.records)) {
          // 情况3: 分页响应格式 {success: true, data: {records: [...]}}
          communityList = response.data.records
        }
      }
      // 情况4: 直接返回数组
      else if (Array.isArray(response)) {
        communityList = response
      }
      // 情况5: 响应在data字段中
      else if (response.data && Array.isArray(response.data)) {
        communityList = response.data
      }
    }
    
    if (communityList && communityList.length > 0) {
      const communityData = communityList
        .filter(item => item && (item.id || item.communityId) && (item.name || item.communityName)) // 过滤无效数据
        .map(item => ({
          label: item.name || item.communityName || '未知社区',
          value: item.id || item.communityId || ''
        }))
      
      if (communityData.length > 0) {
        communityColumns.value = [communityData]
      } else {
        communityColumns.value = [[{
          label: '暂无有效社区数据',
          value: ''
        }]]
      }
    } else {
      communityColumns.value = [[{
        label: '暂无社区数据',
        value: ''
      }]]
    }
  } catch (error) {
    console.error('获取社区列表失败:', error)
    communityColumns.value = [[{
      label: '获取数据失败',
      value: ''
    }]]
    
    // 显示错误提示
    uni.showToast({
      title: '加载社区数据失败',
      icon: 'none'
    })
  }
}

// 表单验证
const validateForm = async () => {
  try {
    // 使用uview-plus的表单验证
    const valid = await formRef.value.validate()
    if (!valid) {
      return false
    }
    
    // 额外验证检查点数据
    for (let i = 0; i < checkpoints.value.length; i++) {
      const checkpoint = checkpoints.value[i]
      if (!checkpoint.name || checkpoint.name.trim() === '') {
        uni.showToast({
          title: `请填写检查点${i + 1}的名称`,
          icon: 'none'
        })
        return false
      }
    }
    
    return true
  } catch (error) {
    console.error('表单验证失败:', error)
    return false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!(await validateForm())) {
    return
  }
  
  try {
    submitting.value = true
    
    const submitData = {
      routeName: formData.routeName,
      routeType: formData.routeType,
      communityId: formData.communityId,
      frequency: formData.frequency,
      durationMinutes: parseInt(formData.durationMinutes),
      description: formData.description,
      checkpoints: checkpoints.value.length > 0 ? checkpoints.value : []
    }
    
    const response = await createSecurityRoute(submitData)
    
    if (response.success) {
      uni.showToast({
        title: '创建成功',
        icon: 'success'
      })
      
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    } else {
      uni.showToast({
        title: response.message || '创建失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('创建失败:', error)
    uni.showToast({
      title: '创建失败，请重试',
      icon: 'none'
    })
  } finally {
    submitting.value = false
  }
}

// 页面加载
onMounted(() => {
  loadCommunityList()
})
</script>

<style lang="scss" scoped>
/* 页面容器 */
.route-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* 服务说明区域 */
.intro-section {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 16px;
  margin: 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  
  .intro-content {
    display: flex;
    align-items: center;
    gap: 12px;
    
    .intro-text {
      flex: 1;
      font-size: 14px;
      color: #666;
      line-height: 1.4;
    }
  }
}

/* 表单容器 */
.form-container {
  flex: 1;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  margin: 0;
  padding: 16px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

/* 表单区块 */
.form-section {
  margin-bottom: 24px;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .section-title {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 12px;
    font-size: 15px;
    font-weight: 600;
    color: #333;
    
    .required {
      color: #f56c6c;
      font-weight: bold;
    }
  }
}

/* 路线类型网格 */
.type-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(80px, 1fr));
  gap: 8px;
  
  .type-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 6px;
    padding: 12px 8px;
    background: #f8f9fa;
    border: 2px solid transparent;
    border-radius: 8px;
    transition: all 0.3s ease;
    
    &.active {
      background: linear-gradient(135deg, #409eff, #67c23a);
      border-color: #409eff;
      color: #fff;
    }
    
    text {
      font-size: 12px;
      text-align: center;
      word-break: break-word;
      line-height: 1.2;
    }
  }
}

/* 巡逻频次网格 */
.frequency-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
  gap: 8px;
  
  .frequency-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 6px;
    padding: 12px 8px;
    background: #f8f9fa;
    border: 2px solid transparent;
    border-radius: 8px;
    transition: all 0.3s ease;
    
    &.active {
      background: linear-gradient(135deg, #409eff, #67c23a);
      border-color: #409eff;
      color: #fff;
    }
    
    text {
      font-size: 12px;
      text-align: center;
      word-break: break-word;
      line-height: 1.2;
    }
  }
}

/* 表单输入框 */
.form-input {
  width: 100%;
  background: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px;
  font-size: 14px;
  
  &:focus {
    border-color: #409eff;
    background: #fff;
  }
}

/* 表单文本域 */
.form-textarea {
  width: 100%;
  background: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px;
  font-size: 14px;
  min-height: 100px;
  
  &:focus {
    border-color: #409eff;
    background: #fff;
  }
}

/* 地址选择器 */
.address-selector {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px;
  
  .address-display {
    flex: 1;
    
    .selected-address {
      font-size: 14px;
      color: #333;
    }
    
    .placeholder {
      font-size: 14px;
      color: #999;
    }
  }
}

/* 检查点配置样式 */
.checkpoint-list {
  margin-bottom: 16px;
}

.checkpoint-item {
  background: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.checkpoint-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  
  .checkpoint-title {
    font-size: 14px;
    font-weight: 600;
    color: #333;
  }
  
  .remove-btn {
    padding: 4px;
    cursor: pointer;
    
    &:active {
      transform: scale(0.9);
    }
  }
}

.checkpoint-form {
  .form-row {
    margin-bottom: 12px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .form-field {
    .field-label {
      display: block;
      font-size: 12px;
      color: #666;
      margin-bottom: 6px;
    }
    
    .field-input {
      width: 100%;
      background: #fff;
      border: 1px solid #e4e7ed;
      border-radius: 6px;
      padding: 8px 12px;
      font-size: 14px;
      
      &:focus {
        border-color: #409eff;
      }
    }
    
    .field-textarea {
      width: 100%;
      background: #fff;
      border: 1px solid #e4e7ed;
      border-radius: 6px;
      padding: 8px 12px;
      font-size: 14px;
      min-height: 60px;
      
      &:focus {
        border-color: #409eff;
      }
    }
  }
}

.add-checkpoint-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  background: #f8f9fa;
  border: 2px dashed #409eff;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:active {
    background: #e6f7ff;
    transform: scale(0.98);
  }
  
  text {
    font-size: 14px;
    color: #409eff;
    font-weight: 500;
  }
}

.optional {
  color: #999;
  font-size: 12px;
  font-weight: normal;
}

/* 提交按钮区域 */
.submit-section {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 16px;
  margin: 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  
  .submit-btn {
    width: 100%;
    background: linear-gradient(135deg, #409eff, #67c23a);
    border: none;
    border-radius: 8px;
    padding: 14px;
    font-size: 16px;
    font-weight: 600;
    color: #fff;
  }
}

/* 响应式设计 */
@media screen and (max-width: 375px) {
  .intro-section,
  .form-container,
  .submit-section {
    padding: 12px;
  }
  
  .form-section {
    margin-bottom: 20px;
  }
  
  .type-grid {
    grid-template-columns: repeat(auto-fit, minmax(70px, 1fr));
    gap: 6px;
  }
  
  .frequency-grid {
    grid-template-columns: repeat(auto-fit, minmax(90px, 1fr));
    gap: 6px;
  }
}

@media screen and (min-width: 414px) {
  .intro-section,
  .form-container,
  .submit-section {
    padding: 20px;
  }
  
  .form-section {
    margin-bottom: 28px;
  }
}

/* 大屏幕适配 */
@media screen and (min-width: 769px) {
  .route-container {
    max-width: 800px;
    margin: 0 auto;
  }
}
</style>